Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

5.5 Running of U-BOOT

5.5.1 U-BOOT Top-Level Loop

The final pointer within the init_sequence_r array must target the run_main_loop function, shifting the system state into an infinite execution loop that waits for user command inputs. The run_main_loop() function is defined inside board_init_r.c and is structured as the following infinite for loop that sequentially invokes main_loop():

static int run_main_loop(void)
{
#ifdef CONFIG_SANDBOX
	sandbox_main_loop_init();
#endif
	for (;;)
		main_loop();
	return 0;
}

The main_loop() function is defined within git/common/main.c, and its implementation code is structured as follows:

void main_loop(void)
{
	const char *s;
	bootstage_mark_name(BOOTSTAGE_ID_MAIN_LOOP, "main_loop");
	if (IS_ENABLED(CONFIG_VERSION_VARIABLE))
		env_set("ver", version_string); /* set version variable */
	cli_init();
	if (IS_ENABLED(CONFIG_USE_PREBOOT))
		run_preboot_environment_command();
	if (IS_ENABLED(CONFIG_UPDATE_TFTP))
		update_tftp(0UL, NULL, NULL);
	s = bootdelay_process();
	if (cli_process_fdt(&s))
		cli_secure_boot_cmd(s);
	autoboot_command(s);
	cli_loop();
	panic("No CLI available");
}

Its primary function is to initialize the command-line interface (CLI) routines, fetch the countdown delay duration via bootdelay_process(), and evaluate the target bootcmd environment variable. The bootcmd variable stores an execution macro or script composed of sequential U-BOOT commands that control how U-BOOT boots the Linux kernel. (The countdown delay can be tuned dynamically via the autodelay environment variable, or specified directly within the Device Tree using the bootdelay integer property, among other configurations). The operational flow of the main_loop() function alongside a streamlined representative slice of the underlying bootcmd script macro is presented below:

Figure 5-11 main_loop() Function Flowchart

bootcmd=run findfdt;
run findtee;
mmc dev ${mmcdev};
if mmc rescan; 
    then if run loadbootscript; 
            then run bootscript; 
         else if run loadimage; 
             then run mmcboot; 
           else run netboot; 
           fi; 
         fi; 
else run netboot; 
fi
loadfdt=fatload mmc ${mmcdev}:${mmcpart} ${fdt_addr} ${fdt_file}
loadimage=fatload mmc ${mmcdev}:${mmcpart} ${loadaddr} ${image}
loadtee=fatload mmc ${mmcdev}:${mmcpart} ${tee_addr} ${tee_file}
mmcboot=echo Booting from mmc ...; 
run mmcargs; 
if test ${tee} = yes; 
    then run loadfdt; 
         run loadtee; 
         bootm ${tee_addr} - ${fdt_addr}; 
else if test ${boot_fdt} = yes || test ${boot_fdt} = try; 
	then if run loadfdt; 
             	then bootz ${loadaddr} - ${fdt_addr}; 
          else if test ${boot_fdt} = try; 
            		then bootz; 
          		else echo WARN: Cannot load the DT;
            	fi; 
            fi; 
	else bootz; 
	fi;
fi;

U-BOOT initially executes the statement run findfdt to process the findfdt macro script. The findfdt macro performs an array of sequential test criteria matching the live motherboard configuration to dynamically resolve and populate the baseline value for the fdt_file environment variable. For brevity, the granular algorithmic details of the findfdt script are omitted here. The fdt_file variable registers the corresponding compiled Device Tree Blob filename matching the physical board; for the imx6qp_sabreauto development board, this evaluates explicitly to fdt_file = imx6qp-sabreauto.dtb. Concurrently, bootcmd runs run findtee to invoke the findtee macro script, which checks for the platform-specific Trusted Execution Environment (TEE) binary payload filename, assigning it to tee_file. Because the imx6qp_sabreauto board implements the uTee-6qpauto hardware security manager firmware, this resolves to tee_file = uTee-6qpauto.

The explicit instruction mmc dev ${mmcdev} configures the active MMC host slot indexed by ${mmcdev} as the primary system boot media target.

When the platform executes a Linux kernel launch sequence originating from an SD card, U-BOOT shifts execution into the run mmcboot macro path. The underlying mmcboot macro runs the child loadimage script, invoking the standard U-BOOT fatload utility block to copy the kernel binary target defined by ${image} from the designated boot partition coordinates (specified explicitly via mmc ${mmcdev}:${mmcpart}) into the physical RAM destination address configured by ${loadaddr}. Following an identical operational framework, the overarching bootcmd macro pulls the target .dtb file and the secure .tee firmware payload into their designated physical memory targets. In this operational context, ${image} maps to a compressed zImage kernel envelope. The absolute boundary coordinates for ${fdt_addr}, ${loadaddr}, and ${tee_addr} are hardcoded or adjusted inside the board architecture configuration header files. Finally, the boot execution sequences handled by the trailing macros—specifically bootm ${tee_addr} - ${fdt_addr} or bootz ${loadaddr} - ${fdt_addr}—execute the definitive jump into the Linux kernel initialization path.

The bootcmd macro string is maintained directly within U-BOOT’s persistent non-volatile environment space; its default fallback string value is established at compile time within the generic platform configuration templates located at git/include/configs/<board_common>.h. End-users can interrupt the automatic autoboot countdown sequence to drop into the interactive U-BOOT command-line shell, modify the configuration properties of bootcmd manually, and commit the updated script permanently to flash blocks via the saveenv routine.

If the active Device Tree configuration implements a custom bootcmd node property block, the parsing routines inside main_loop() interrogate the tree to verify whether an explicit bootsecure enforcement flag has been enabled. If the bootsecure flag is active, the system branches immediately into an unreturned secure encrypted boot execution routine (cli_secure_boot_cmd). If the verification pass confirms standard booting operations, execution control passes to the autoboot_command() block. The autoboot_command() function evaluates the live tracking timer parameters alongside the console UART inputs to check if a user keystroke has been registered. If the timeout delay expires without catching an active keyboard interrupt vector, it calls run_command_list() to interpret and run the compiled bootcmd command sequence fetched by the bootdelay_process() routine. Conversely, if a valid keystroke is caught during the active countdown delay window, the state machine diverts into the cli_loop() function block, initializing the persistent shell loop to parse, interpret, and execute incoming text commands manually supplied by the developer.

5.5.2 U-BOOT Command Interpretation

The run_command_list function parses U-BOOT scripts. U-BOOT can evaluate scripts or commands using either the legacy simple parser or the HUSH parser (detailed in subsequent sections). When configured for the simple interpretation path, it invokes cli_simple_run_command_list to process the script. The C implementation code for run_command_list under this simple interpretation profile is structured as follows:

int run_command_list(const char *cmd, int len, int flag)
{
    int need_buff = 1;
    char *buff = (char *)cmd; /* cast away const */
    int rcode = 0;
    if (len == -1) {
        len = strlen(cmd);
        need_buff = strchr(cmd, '\n') != NULL;
    }
    if (need_buff) {
        buff = malloc(len + 1);
        if (!buff)
            return 1;
        memcpy(buff, cmd, len);
        buff[len] = '\0';
    }
    rcode = cli_simple_run_command_list(buff, flag);
    if (need_buff)
        free(buff);
    return rcode;
}

This code first calculates the length of the cmd string (passed dynamically to cmd via the bootcmd variable within the main_loop). If the cmd string encapsulates newline characters ('\n'), the routine allocates a dynamic buffer, replaces occurrences of '\n' with null terminators ('\0'), copies the command block into this isolated buffer memory, and finally invokes cli_simple_run_command_list to execute the script referenced by buff.

5.5.3 U-BOOT Command Execution

The functional role of cli_simple_run_command_list() is to split the script pointed to by cmd into distinct sub-units delimited by newline boundaries ('\n'), and then sequentially call cli_simple_run_command() to execute each unit's command string. cli_simple_run_command() parses the text stream provided by cli_simple_run_command_list and sections it into multiple tokens separated by semicolons (;).

If any tokens contain macros wrapped inside ${} or $(), the routine calls cli_simple_process_macro() to dynamically substitute the macros with their current expanded environment values. It then leverages cli_simple_parse_line() to tokenize the expanded string into an array of individual, whitespace-delimited argument variables.

These resolved variables are stored sequentially inside the argv array, where argv[0] holds the primary command binary string, and subsequent entries like argv[1] map to the trailing arguments passed to the utility; the total argument count is registered inside the integer variable argc. Finally, cli_simple_run_command() calls cmd_process() to execute the explicit command specified by argv[0].

The cmd_process() function first leverages find_cmd(argv[0]) to query the internal link-time command table for a matching tracking entry corresponding to argv[0]. If a valid entry is resolved, it passes the command's structural argument count and argument vector array over to the cmd_call() infrastructure to execute the operation. Within the source file git/cmd/bootm.c, a core macro declaration is defined as follows:

U_BOOT_CMD(bootm, CONFIG_SYS_MAXARGS, 1, do_bootm, 
  "boot application image from memory", bootm_help_text);

This macro architecture is defined within the core header file git/include/command.h. In this declaration, bootm specifies the text command string, CONFIG_SYS_MAXARGS defines the maximum argument threshold permitted by the utility, 1 indicates that hitting the carriage return key will repeat the execution of the previous command string, and do_bootm acts as the definitive C callback handler function pointer. When an operator issues the bootm string, U-BOOT handles the invocation by executing the underlying C function do_bootm. The string "boot application image from memory" provides a short summary description, while bootm_help_text stores the exhaustive help documentation.

Expanding this structural macro shows that the statement expands to the following link-time initialization code:

ll_entry_declare(cmd_table_t, bootm, do_bootm) = {
    "bootm", CONFIG_SYS_MAXARGS, cmd_always_repeatable, do_bootm, "boot application image from memory", bootm_help_text, NULL
};

The compilation layout defines a unique static tracking structure of type struct cmd_tbl named _u_boot_list_2_cmd_2_bootm, which is placed within the custom linker section .u_boot_list_2_cmd_2_bootm. The final generated variable assignment maps to the following definition:

struct cmd_tbl _u_boot_list_2_cmd_2_bootm = {
    .name       = "bootm",                                   // Command string token
    .maxargs    = CONFIG_SYS_MAXARGS,                        // Maximum parameter count threshold
    .repeatable = 1,                                         // Repeatable execution flag on Enter keypress
    .cmd        = do_bootm,                                  // Function pointer: target logic execution loop
    .usage      = "boot application image from memory",     // Short description string (shown by generic 'help')
    .help       = bootm_help_text,                          // Long description string (shown by 'help bootm')
    .complete   = NULL                                       // Auto-completion hook callback (Null assigned here)
};

This mechanism links the command registry key "bootm" directly to the do_bootm C routine. The structural execution architecture tracking the run_command_list function is mapped out in the technical flowchart below:

Figure 5-12 run_command_list() Function Flowchart

When launching a Linux kernel from an attached SD card, the cmd_call() infrastructure invokes cmd_always_repeatable(), which subsequently triggers the execution entry point of do_bootm(). Consequently, cmd_call() routes execution straight into do_bootm() to drive the final Linux booting sequence forward.

If the platform is compiled to leverage an early pre-boot environment pathway, the main_loop processes the pre-boot commands before parsing other variables. Furthermore, if network-based recovery configurations are enabled, the main_loop invokes upstream network protocols using the TFTP framework to pull down and flash updated U-BOOT and Linux kernel images before continuing routine execution loops.

5.5.4 Command Processing and Execution

At its termination phase, the main_loop function transitions into the interactive command-line interface framework loop (cli_loop), where it pauses to capture manual command strings supplied by the operator or awaits the expiration of the autoboot countdown delay vector to initiate the automated booting pathway.

The cli_loop() function is defined within the source file git/common/cli.c, and its technical implementation is structured as follows:

void cli_loop(void)
{
	bootstage_mark(BOOTSTAGE_ID_ENTER_CLI_LOOP);
#ifdef CONFIG_HUSH_PARSER
	parse_file_outer();
	/* This point is never reached */
	for (;;);
#elif defined(CONFIG_CMDLINE)
	cli_simple_loop();
#else
	printf("## U-BOOT command line is disabled. Please enable CONFIG_CMDLINE\n");
#endif /*CONFIG_HUSH_PARSER*/
}

The system is architected to parse operator commands utilizing either the Bourne-shell-compatible HUSH parser or the legacy simple interface engine; the targeted translation model is explicitly dictated at build time via preprocessor configuration flags. The structural parsing of an incoming command line string is a sequential process of stream scanning and string tokenization. Because the underlying logic is linear, it is omitted here; interested developers can audit the parsing routines maintained inside git/common/cli_hush.c or git/common/cli_simple.c. To establish a baseline reference model, the utility execution pipeline is illustrated here by analyzing the workflow of the cli_simple_loop() sub-routine.

The cli_simple_loop() function is implemented as an infinite for(;;) execution loop. Inside this infinite loop block, the engine polls the active console device to sample user inputs and subsequently parses the captured string. If the token validation pass confirms a legal command structure, the system triggers the underlying execution logic mapped to that utility. Concurrently, it commits the verified command string to a localized history buffer, enabling the user to traverse and re-execute historical command vectors using the terminal's up and down arrow keys. Once the routine concludes, it recycles its tracking flags and returns to a block-waiting state to catch subsequent text streams.

U-BOOT exports an exceptionally rich and comprehensive suite of native utilities, predominantly categorized into hardware telemetry information gathering, low-level memory block manipulation, non-volatile flash programming, runtime execution flow control, transport layer network stack management, and environment variable manipulation, alongside generalized hardware interface control and bare-metal debugging routines. Furthermore, the bootloader incorporates structural abstraction layers supporting standard Linux file systems.

Leveraging this combined framework of commands and environment variables, U-BOOT exercises absolute control over the Linux kernel loading topology and boot pathways, allowing developers to configure and test custom hardware setups interactively. When U-BOOT is resting in its command interpreter state, executing the printenv utility dumps a full listing of all active global environment variables to the console terminal, exposing the precise booting vectors under which the current platform is running.

The programmatic definitions declaring these U-BOOT commands are distributed across distinct C resource files clustered within the git/cmd/, git/lib/, and git/common/ directories of the source tree. A single source module can isolate a standalone monolithic command definition or aggregate multiple related sub-commands into a unified register table. Developers seeking deep structural details regarding particular command arrays can audit the corresponding C source targets contained within those paths.

Copyright © 2026 Guangzhou eSmart Information Technology Co., Ltd. All Rights Reserved.
All content in this book is copyrighted by the author. For personal learning and exchange only. Commercial use without authorization is strictly prohibited. Email:

✉ 3348194517@qq.com | hai616878@gmail.com